package com.hundsun.cprs.yyt.util.profiler;

import org.apache.commons.lang.ClassUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author linrl
 * @date 2018年4月20日
 */
@Aspect
@Component
public class TimeProfilerAspect {
    
    private static final Log logger = LogFactory.getLog(TimeProfilerAspect.class);
    
    @Pointcut("execution(* com.hundsun.cprs.yyt..*Service*.*(..)) || "
        + "execution(* com.hundsun.cprs.yyt..*Dao*.*(..)) || "
        + "execution(* com.hundsun.cprs.yyt..*Filter.*(..)) ||"
        + "execution(* com.hundsun.cprs.yyt..*Listener.*(..))")
    public void accessLogInGatewayModule(){};
    
    @Around(value = "accessLogInGatewayModule()")
    public Object accessLogInGatewayCalls(ProceedingJoinPoint joinPoint) throws Throwable{
        if (TimeProfiler.isProfileEnable()) {
            return invokeWithProfile(joinPoint);
        } else {
            return joinPoint.proceed();
        }
    }
    
    @SuppressWarnings("unchecked")
    private Object invokeWithProfile(ProceedingJoinPoint joinPoint) throws Throwable{
        String methodName = joinPoint.getSignature().getName();
        Class clazz = joinPoint.getTarget().getClass();
        String className = ClassUtils.getShortClassName(clazz);
        TimeProfiler.beginTask(new StringBuilder(className).append(':').append(methodName).toString());
        Object ret;
        try {
            ret = joinPoint.proceed();
        } finally {
            TimeProfiler.endTask();
        }
        return ret;
    }
}
